<script setup lang="ts">
import type { Api, Options } from '@form-create/element-ui'
import type { SysSettings } from '@/apis/system/sysSettingApi'
import formCreate from '@form-create/element-ui'
import { onMounted, ref, watch } from 'vue'
import { sysSettingsApi } from '@/apis/system/sysSettingApi'

const { settings } = defineProps<{
  disabled?: boolean
  settings: SysSettings
}>()

onMounted(loadData)
watch(() => settings, loadData)

const settingFormData = ref<any>({})
const settingFormRules = ref<any[]>([])

async function loadData() {
  settingFormData.value = settings.settingsData ? JSON.parse(settings.settingsData!) : undefined
  settingFormRules.value = settings.settingsSchema ? JSON.parse(settings.settingsSchema!) : undefined
}
const FormCreate = formCreate.$form()
const api = ref<Api>()
const options = ref<Options>({
  submitBtn: false,
})

async function submit() {
  await api.value?.submit(async (formData) => {
    await sysSettingsApi.modifyData({
      id: settings.id,
      settingsData: JSON.stringify(formData),
    })
    ElMessage.success('保存成功')
  })
}

async function validate() {
  await api.value?.validate()
}

defineExpose({ submit, validate })
</script>

<template>
  <FormCreate v-model:api="api" v-model="settingFormData" :rule="settingFormRules" :option="options" :disabled="disabled" />
</template>
